package com.ljy.my_study.java.juc.synchronousqueue;

import java.util.concurrent.SynchronousQueue;

/**
 * @author lijunying
 * @date 2021/2/1 14:47
 */
public class SynchronousQueueTestMain {

    //调用take方法，put和take的线程都会解锁
    public static void main(String[] args) {
        SynchronousQueue<Integer> queue=new SynchronousQueue<>();
        Runnable putRunnable=()->{
            try {
                int num=(int)(Math.random()*100);
                System.out.println(Thread.currentThread().getName()+" put "+num+" start.");
                queue.put(num);
                System.out.println(Thread.currentThread().getName()+" put "+num+" end.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

        Runnable takeRunnable=()->{
            try {
                System.out.println(Thread.currentThread().getName()+" take start.");
                Thread.sleep(1000L);
                System.out.println(Thread.currentThread().getName()+" take "+queue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };
        int count=3;
        for(int i=0;i<count;i++){
            new Thread(takeRunnable).start();
        }
//        takeRunnable.run();
        System.out.println("");
        for(int i=0;i<count;i++){
            new Thread(putRunnable).start();
        }
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
